package com.da.javatest.niuke.baodian;

import java.util.Arrays;

/**
 * @author chenlida
 * @date 2020/10/8 10:04
 * https://www.nowcoder.com/practice/33ad4d168a3247b9b63f41e4eaded652?tpId=8&tags=&title=&diffculty=0&judgeStatus=0&rp=1
 */
public class C28CloseNumber {
    public int[] getCloseNumber(int x) {
        return new int[] {getSmallNumber(x), getBigNumber(x)};
    }

    private int getSmallNumber(int x) {
        String s = Integer.toBinaryString(x);
        int count = getCount(s);
        for (int i = x - 1; i > 0; i--) {
            if (getCount(Integer.toBinaryString(i)) == count) {
                return i;
            }
        }
        return x;
    }

    private int getBigNumber(int x) {
        String s = Integer.toBinaryString(x);
        int count = getCount(s);
        while (true) {
            if (getCount(Integer.toBinaryString(++x)) == count) {
                return x;
            }
        }
    }

    private int getCount(String binaryString) {
        char[] chars = binaryString.toCharArray();
        int count = 0;
        for (char c : chars) {
            if (c == '1') {
                count++;
            }
        }
        return count;
    }

    public int[] getCloseNumber2(int x) {
        int min = x - 1, max = x + 1;
        while (Integer.bitCount(x) != Integer.bitCount(min) && min >= 0) {
            min--;
        }

        while (Integer.bitCount(x) != Integer.bitCount(max)) {
            max++;
        }
        return new int[] {min, max};
    }

    public static void main(String[] args) {
        C28CloseNumber test = new C28CloseNumber();
        System.out.println(Arrays.toString(test.getCloseNumber(2)));
        System.out.println(Arrays.toString(test.getCloseNumber(14)));
        System.out.println("-------------------------------");
        System.out.println(Arrays.toString(test.getCloseNumber2(2)));
        System.out.println(Arrays.toString(test.getCloseNumber2(14)));
    }
}
